package com.example.project.interceptor;

import com.example.project.annotation.AdminRequired;
import com.example.project.entity.User;
import com.example.project.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AdminRequired adminRequired = handlerMethod.getMethodAnnotation(AdminRequired.class);
        if (adminRequired == null) {
            return true;
        }

        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            response.setStatus(401);
            return false;
        }

        Long userId = (Long) userIdObj;
        User user = userMapper.selectById(userId);
        if (user == null || user.getRoleId() != 1L) {
            response.setStatus(403);
            return false;
        }

        return true;
    }
} 